local UIBase = require("view.UIBase")
local PopupChooseEquipment = class("PopupChooseEquipment", UIBase)

local CARD_NUM = 5

function PopupChooseEquipment:ctor()
    local resource = {
        path = "Prefabs/Popup",
        name = "PopupChooseEquipment",
        canvas = 3
    }
end

function PopupChooseEquipment:setEquipId(equipId)
    self._equipId = equipId
end

function PopupChooseEquipment:setCallback(callback)
    self._callback = callback
end

function PopupChooseEquipment:start()
    self._btnOk.onClick:AddListener(handler(self, self._onBtnOkClick))
    self._btnClose.onClick:AddListener(handler(self, self._onBtnCloseClick))
    self._listView:SetTemplate(
        handler(self, self._onItemUpdate),
        handler(self, self._onValueChange),
        handler(self, self._onItemTouch)
    )
    self._dataList = G_UserData:getEquipment():getEquipmentList(self._equipId)
    local count = math.ceil(#self._dataList / CARD_NUM)
    self._listView:ReSize(count)
end

function PopupChooseEquipment:onClose()
end

function PopupChooseEquipment:_onItemUpdate(item, index)
    local startIndex = index * CARD_NUM + 1
    local endIndex = startIndex + CARD_NUM - 1
    local lines = {}
    for i = startIndex, endIndex do
        local data = self._dataList[i]
        if data then
            table.insert(lines, data)
        end
    end
    item:updateUI(lines, self._selectedEquipId)
end

function PopupChooseEquipment:_onValueChange()
end

function PopupChooseEquipment:_onItemTouch(item, equipId)
    if self._selectedEquipId == equipId then
        return
    end
    self._selectedEquipId = equipId
    printDebug("PopupChooseEquipment:_onItemTouch " .. equipId)
    self._listView:UpdateUsedCell()
end

function PopupChooseEquipment:_onBtnOkClick(event)
    if self._callback then
        self._callback(self._selectedEquipId)
    end
    self:close()
end

function PopupChooseEquipment:_onBtnCloseClick()
    self:close()
end

return PopupChooseEquipment
